﻿import os
from flask import Flask, send_from_directory, abort, request
import pyautogui
import time
import json
import shutil
import datetime

from click_and_type import click_and_type_at_coordinates, input_info
from foursightcontrol import get_zenik_value, test

app = Flask(__name__)

# 定义文件存储的目录
# FILE_DIRECTORY = r"C:\Users\PhaseCam\Desktop\inferanceSample"  # 这里替换为你实际存储文件的路径
VIEW_SCREEN_SHOT = "D:\\view" # 摄像头截图保存地址

FILE_DIRECTORY = r"F:\PI\huiyanproject_4D\huiyanproject\autotools\inferenceSample"

def get_inference_sample():
    file_name = str(datetime.datetime.now()).split(".")[0]
    file_name = file_name.replace(" ", "_").replace(":", "_")
    file_path = os.path.join(FILE_DIRECTORY, f"{file_name}.png")
    print("file_path =", file_path)
    screenshot = pyautogui.screenshot(region=(400, 150, 750, 800))
    screenshot.save(file_path)
    return file_path

@app.route('/download/<filename>', methods=['GET'])
def download_file(filename):
    try:
        # 生成文件的绝对路径
        file_path = os.path.join(FILE_DIRECTORY, filename)

        # 检查文件是否存在以及路径是否安全
        if os.path.exists(file_path) and os.path.isfile(file_path):
            # 使用 send_from_directory 提供文件下载
            return send_from_directory(FILE_DIRECTORY, filename, as_attachment=True)
        else:
            abort(404)  # 如果文件不存在或路径不安全，返回404错误
    except Exception as e:
        print(f"Error: {e}")
        abort(500)  # 返回500内部错误

def get_latest_file(directory):
    # 获取目录中的所有文件路径
    files = [os.path.join(directory, f) for f in os.listdir(directory) if os.path.isfile(os.path.join(directory, f))]
    
    # 如果目录为空，返回 None
    if not files:
        return None

    # 通过创建时间找到最新的文件
    latest_file = max(files, key=os.path.getctime)
    
    return latest_file
    
def copy_latest_file_to_directory(src_file_path, dest_directory):
    
    if src_file_path:
        # 获取文件名
        file_name = os.path.basename(src_file_path)
        
        # 构建目标文件路径
        dest_path = os.path.join(dest_directory, file_name)
        
        # 复制文件到指定路径
        shutil.copy(src_file_path, dest_path)
        
        print(f"已将最新的文件 '{file_name}' 复制到目标目录: {dest_directory}")
    else:
        print("源目录中没有文件")

# 摄像头截图
def take_screenshot_of_view():
    pyautogui.hotkey('ctrl', 'alt', 'r') # 软件截图
    time.sleep(4)
    view_pic_path = get_latest_file(VIEW_SCREEN_SHOT) # 获取截图
    copy_latest_file_to_directory(view_pic_path, FILE_DIRECTORY)
    return view_pic_path

# 干涉图样截图    
def take_screenshot_of_interfere():
    time.sleep(1)
    return get_inference_sample()

def load_pos_info():
    file_path = os.path.join(os.path.dirname(__file__), "location.json")
    with open(file_path, 'r', encoding='utf-8') as file:
        return json.load(file)

# 新增处理截屏请求的POST接口
@app.route('/screenshot', methods=['POST'])
def screenshot():
    data = request.json # 截屏参数
    operator = data.get("operator") 
    if operator == "viewer": # 摄像头截屏操作
        try:
            # 执行截屏操作
            screenshot_path = take_screenshot_of_view()

            # 检查截屏是否成功
            if screenshot_path:
                return json.dumps({"message": "Screenshot taken successfully", "screenshot_path": screenshot_path}), 200
            else:
                return json.dumps({"error": "Failed to take screenshot"}), 500
        except Exception as e:
            print(f"Error: {e}")
            return json.dumps({"error": str(e)}), 500
    elif operator == "hexor": # 六自由度转台操作
        pos_info = load_pos_info()
        control_list = data.get("control_list")
        print("control_list ====", control_list)
        for control in control_list:
            soft_name = control['soft_name']
            if pos_info.get(soft_name):
                pos_x, pos_y = pos_info.get(soft_name)
                print("pos_x, pos_y ====", pos_x, pos_y)
                input_value = control['input']
                right_click = True if control['click_type'] == "right" else False
                click_num = control['click_num']
                time_sleep = control['time_sleep']
                press_enter = control.get('press_enter')
                click_and_type_at_coordinates(pos_x, pos_y, text=input_value, right_click=right_click, clicks=click_num, press_enter=press_enter, time_sleep=time_sleep)
                print(f"{soft_name} operate ok")
            elif soft_name == None:
                input_value = control['input']
                press_enter = control['press_enter']
                time_sleep = control['time_sleep']
                input_info(input_value=input_value, press_enter=press_enter, time_sleep=time_sleep)
            else:
                print(f"Error:{soft_name} pos is null")
        return json.dumps({"message": "hexor control successfully"}), 200
    elif operator == "interfere": # 干涉图样截屏操作
        try:
            # 执行截屏操作
            screenshot_path = take_screenshot_of_interfere()

            # 检查截屏是否成功
            if screenshot_path:
                return json.dumps({"message": "Screenshot taken successfully", "screenshot_path": screenshot_path}), 200
            else:
                return json.dumps({"error": "Failed to take screenshot"}), 500
        except Exception as e:
            print(f"Error: {e}")
            return json.dumps({"error": str(e)}), 500
    elif operator == "zenik": # 获取zenik系数
        try:
            zenik_value = get_zenik_value()
            # zenik_value = test()
            return json.dumps({"message": "zenik got successfully", "zenik": zenik_value}), 200
        except Exception as e:
            print(f"Error: {e}")
            return json.dumps({"error": str(e)}), 500
            
if __name__ == '__main__':
    app.run(host="0.0.0.0", port="9052", debug=False)
    #time.sleep(5)
    #get_inference_sample()
    
